
package com.bolt.support.dynamic.datasource.aop;


import com.bolt.common.utils.StrUtil;
import com.bolt.support.dynamic.datasource.tx.LocalTxUtil;
import com.bolt.support.dynamic.datasource.tx.TransactionContext;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DynamicLocalTransactionInterceptor implements MethodInterceptor {

    private final Logger log = LoggerFactory.getLogger(DynamicLocalTransactionInterceptor.class);

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (!StrUtil.isEmpty(TransactionContext.getXID())) {
            return methodInvocation.proceed();
        }
        boolean state = true;
        Object o;
        LocalTxUtil.startTransaction();
        try {
            o = methodInvocation.proceed();
        } catch (Exception e) {
            state = false;
            throw e;
        } finally {
            if (state) {
                LocalTxUtil.commit();
            } else {
                LocalTxUtil.rollback();
            }
        }
        return o;
    }
}
